package com.java110.api.listener.electric;

import com.alibaba.fastjson.JSONObject;
import com.java110.api.listener.AbstractServiceApiListener;
import com.java110.core.annotation.Java110Listener;
import com.java110.core.context.DataFlowContext;
import com.java110.core.event.service.api.ServiceDataFlowEvent;
import com.java110.dto.machine.MachineDto;
import com.java110.dto.meterWater.MeterWaterDto;
import com.java110.dto.meterWater.WeDto;
import com.java110.intf.fee.IMeterWaterInnerServiceSMO;
import com.java110.utils.constant.ServiceCodeConstant;
import com.java110.utils.util.BeanConvertUtil;
import com.java110.vo.ResultVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.ArrayList;
import java.util.List;

@Java110Listener("weListListener")
public class WeListListener extends AbstractServiceApiListener {

    @Autowired
    private IMeterWaterInnerServiceSMO meterWaterInnerServiceSMOImpl;

    private static Logger logger = LoggerFactory.getLogger(WeListListener.class);
    @Override
    public String getServiceCode() {
        return "we.list";
    }

    @Override
    public HttpMethod getHttpMethod() {
        return HttpMethod.POST;
    }

    @Override
    protected void validate(ServiceDataFlowEvent event, JSONObject reqJson) {

    }

    @Override
    protected void doSoService(ServiceDataFlowEvent event, DataFlowContext context, JSONObject reqJson) {
        logger.debug("WeSaveListener : {}", event);
        DataFlowContext dataFlowContext = event.getDataFlowContext();
        WeDto dto = BeanConvertUtil.covertBean(reqJson, WeDto.class);
        ResultVo resultVo = null;
        int count = meterWaterInnerServiceSMOImpl.countWes(dto);

        int page = dto.getPage();
        if(page < 1){
            page = 1;
        }
        int row = dto.getRow() < 0 ? 10 : dto.getRow();
        page = (page - 1) * row;
        dto.setRow(row);
        dto.setPage(page);

        List<WeDto> meterWaterDtos = meterWaterInnerServiceSMOImpl.queryWes(dto);

        resultVo = new ResultVo((int) Math.ceil((double) count / (double) reqJson.getInteger("row")), count, meterWaterDtos);

        ResponseEntity<String> responseEntity = new ResponseEntity<String>(resultVo.toString(), HttpStatus.OK);

        context.setResponseEntity(responseEntity);
    }


    @Override
    public int getOrder() {
        return 0;
    }
}
